package com.sun.androidexerciseproject.widget.mvvm.ui.view;

import android.app.Application;
import android.databinding.ObservableField;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;

import com.sun.androidexerciseproject.widget.activity.ui.MainActivity;
import com.sun.androidexerciseproject.widget.mvvm.model.DemoRepository;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class LoginViewModel extends BaseViewModel<DemoRepository> {
    //用户名绑定
    public ObservableField<String> userName = new ObservableField<>();

    public ObservableField<String> pwd = new ObservableField<>();

    public LoginViewModel(@NonNull Application application) {
        super(application);
    }


    public View.OnClickListener loginOnClick = v -> login();

    /**
     * 登录事件
     */
    private void login() {
        if (TextUtils.isEmpty(userName.get())) {
            ToastUtils.showShort("请输入账户！");
            return;
        }
        if (TextUtils.isEmpty(pwd.get())) {
            ToastUtils.showShort("请输入密码！");
            return;
        }
        addSubscribe(model.login()
                .compose(RxUtils.schedulersTransformer())
                .doOnDispose(() -> showDialog())
                .subscribe(o -> {
                    dismissDialog();
                    model.saveUserName(userName.get());
                    model.savePassword(pwd.get());
                    startActivity(MainActivity.class);
                    finish();
                })
        );

    }
}
